// 加载数据
import { data1 } from './data.js';
import { data2 } from './data.js';
import { data3 } from './data.js';
import { data4 } from './data.js';

// createPages 
import { createPages } from './createPages.js';
// homePage 动态阴影效果
import { shadow } from './shadow.js';

window.onload = () => {
    const dataArr = [];
    dataArr.push(data1, data2, data3);

    // 创建 homePage 数据
    const classArr = [];
    dataArr.forEach((item) => {
        classArr.push(item[0].title);
    });
    const homePage = {
        title: 'blueJ-51班-冉腾腾',
        classify: classArr,
    };
    // 插入 homePage 数据
    dataArr.unshift(homePage);
    console.log(dataArr);

    // 绑定容器
    const container = document.querySelector('.container');

    // 默认显示页面
    let currentIndex = 0;

    // 创建页面
    let { createItem, resetElements } = { ...createPages(dataArr, container) };
    resetElements(currentIndex);
    shadow();


    // 创建动画锁 默认关闭
    let isAnimating = false;
    // ctrl按键锁 防止页面滚动与浏览器缩放冲突
    let keyLock = false;
    // 鼠标锁 禁止鼠标滑轮切换页面
    let mouseLock = false;

    // 页面 向上/向下 切换
    function scrollUp() {
        container.classList.add('scroll-up');
        currentIndex = currentIndex - 1 < 0 ? dataArr.length - 1 : currentIndex - 1;
        ctrlActive(currentIndex);
    }
    function scrollDown() {
        container.classList.add('scroll-down');
        currentIndex = currentIndex + 1 >= dataArr.length ? 0 : currentIndex + 1;
        ctrlActive(currentIndex);
    }

    // 监听滚动条滚动方向 向下为正值，向上为负值
    function scroll(e) {
        // 排除特殊情况 
        if (!e.deltaY) return;

        // 按键锁、鼠标锁、动画锁
        if (keyLock) return;
        if (mouseLock) return;
        if (isAnimating) return;
        isAnimating = true;

        if (e.deltaY > 0) {
            scrollDown();
        } else {
            scrollUp();
        }
    }
    container.onwheel = e => scroll(e);

    window.onkeydown = (e) => {
        if (isAnimating) return;

        if (e.keyCode == 40) {
            scrollDown();
            isAnimating = true;
        } else if (e.keyCode == 38) {
            scrollUp();
            isAnimating = true;
        }

        if (e.keyCode == 17) {
            container.onwheel = null;
            keyLock = true;
        };
    }
    window.onkeyup = (e) => {
        if (e.keyCode == 17) {
            container.onwheel = e => scroll(e);
            keyLock = false;
        };
    };

    // 动画结束事件
    container.addEventListener('transitionend', (e) => {
        if (e.target.classList[0] != 'item') return;
        isAnimating = false;
        container.classList.remove('scroll-down');
        container.classList.remove('scroll-up');
        resetElements(currentIndex);
        // 保留homePage页事件
        home();
        item();
    })

    // 创建控制面板
    const ctrlContent = document.querySelector('.controlPanel>ul');
    dataArr.forEach((item, index) => {
        const li = document.createElement('li');
        li.setAttribute('data-id', index);
        if (index == 0) {
            li.innerHTML = `冉腾腾`;
        } else {
            li.innerHTML = item[0].title;
        }
        ctrlContent.appendChild(li);
    })

    // li手风琴效果
    function ctrlActive(index) {
        const li = ctrlContent.querySelectorAll('li');
        li.forEach((item) => {
            item.classList.remove('active');
        })
        li[index].classList.add('active');
    }

    // 点击li切换到对应页面（事件委托）
    ctrlContent.onclick = (e) => {
        e.stopPropagation();
        if (isAnimating) return;

        let oldInd = currentIndex;
        if (e.target.nodeName == 'LI') {
            isAnimating = true;
            const li = ctrlContent.querySelectorAll('li');

            let ind = Number(e.target.getAttribute('data-id'));
            if (ind == oldInd) {
                isAnimating = false;
                return;
            }

            ctrlActive(ind);

            // 跳转至下 n 个
            if (ind > oldInd) {
                const nextItem = document.querySelector('.item.next');
                createItem(ind).className = 'item next newItem';
                const newItem = container.querySelector('.newItem')
                container.replaceChild(newItem, nextItem)
                setTimeout(() => {
                    container.classList.add('scroll-down');
                }, 1)
            }
            // 跳转至上 n 个
            if (ind < oldInd) {
                const prevItem = document.querySelector('.item.prev');
                createItem(ind).className = 'item prev newItem';
                const newItem = container.querySelector('.newItem')
                container.replaceChild(newItem, prevItem)
                setTimeout(() => {
                    container.classList.add('scroll-up');
                }, 1)
            }
            // 更新当前下标
            currentIndex = ind;
        }
    }
    ctrlActive(currentIndex);

    // 上一页/下一页按钮（事件委托）
    const ctrlPanel = document.querySelector(".controlPanel");
    ctrlPanel.addEventListener('click', (e) => {
        if (isAnimating) return;
        isAnimating = true;

        if (e.target.className == 'prevBtn') {
            scrollUp();
        } else if (e.target.className == 'nextBtn') {
            scrollDown();
        } else {
            isAnimating = false;
        }

        if (e.target.classList[0] == "mouseLock") {
            e.target.classList.toggle('mLock_Active');
            if (e.target.classList[1]) {
                mouseLock = true;
            } else {
                mouseLock = false;
            }
        }
    });

    // homePage页操作
    function home() {
        const homeBtn = document.querySelectorAll('.homePage li');
        homeBtn.forEach((item, index) => {
            item.onclick = () => {
                isAnimating = true;
                const nextItem = document.querySelector('.item.next');
                createItem(index + 1).className = 'item next newItem';
                const newItem = container.querySelector('.newItem')
                container.replaceChild(newItem, nextItem)
                setTimeout(() => {
                    container.classList.add('scroll-down');
                }, 1)
                // 更新当前下标
                currentIndex = index + 1;
                // 更新控制面板
                ctrlActive(currentIndex);
            }
        })
    };
    home();

    function item() {
        const itemBox = container.querySelectorAll('.itemPage');
        itemBox.forEach((item) => {
            item.addEventListener('mouseenter', () => {
                container.onwheel = null;
            })
            item.addEventListener('mouseleave', () => {
                if (keyLock) return;
                container.onwheel = e => scroll(e);
            })

            // 打开/关闭卡片
            item.addEventListener('click', (e) => {
                if (e.target.nodeName == "DIV") {
                    e.target.classList.toggle('show');
                }
            })
        })
    };
    item();

    console.log();
    // let con = document.querySelector('.preWindow')
    // con.innerHTML = marked.parse('# Marked in the browser\n\nRendered by **marked**.');
};